package mybatis.generator.sample.mapper;

import mybatis.generator.BaseMapper;
import mybatis.generator.FilterType;
import mybatis.generator.annotation.ExecuteInsert;
import mybatis.generator.annotation.ExecuteSelect;
import mybatis.generator.annotation.FilterParam;
import mybatis.generator.ext.AdditionalColumnValue;
import mybatis.generator.ext.AdditionalFilter;
import mybatis.generator.ext.InterceptorContext;
import mybatis.generator.sample.UserController;
import mybatis.generator.sample.entity.User;
import mybatis.generator.sample.model.UserQuery;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by dave on 18-5-20 上午10:44.
 */
@Mapper
public interface UserMapper extends BaseMapper<User, Long> {

    @ExecuteInsert
    int insertU(UserController.U u);

    @ExecuteInsert
    int insertWithMap(Map<String, Object> map);

    @ExecuteInsert(interceptor = "interceptInsertAll")
    int insertAll(List<User> users);

    @Insert("insert into user(name, phone)values(#{name},#{phone})")
    @Options(useGeneratedKeys = true)
    int insertUseOption(User user);

    @ExecuteSelect(interceptor = "interceptGetList")
    List<User> getList(@FilterParam UserQuery query, @FilterParam("name") String name);

    static void interceptGetList(InterceptorContext context) {
        AdditionalFilter af = new AdditionalFilter("user", "create_time", new Date(new Date().getTime() - 60_000));
        af.setType(FilterType.gt);
        context.getAdditionalFilters().add(af);
    }

    default void interceptInsertAll(InterceptorContext context) throws ParseException {
        AdditionalColumnValue cv = AdditionalColumnValue.byEntityField("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2019-01-01 00:00:00"));
        cv.setOverride(true);
        context.addAdditionalColumnValue(cv);
    }
}
